package com.fancy.learncenter.ui.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.CartoonClassListBean;
import com.fancy.learncenter.bean.CartoonJoinClassResultBean;
import com.fancy.learncenter.bean.CartoonRoleDataBean;
import com.fancy.learncenter.bean.CartoonTeacherListClassDataBean;
import com.fancy.learncenter.bean.CheckCreatClassDataBean;
import com.fancy.learncenter.common.MyApplication;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.CartoonChildHomeActivity;
import com.fancy.learncenter.ui.activity.CartoonCreatClassActivity;
import com.fancy.learncenter.ui.activity.CartoonSearchActivity;
import com.fancy.learncenter.ui.activity.MainActivity;
import com.fancy.learncenter.ui.adapter.CartoonTeacherClassListAdapter;
import com.fancy.learncenter.ui.view.PromptPopupWindow;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.SPUtils;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class NewSchoolFragment extends Fragment {
    @Bind(R.id.select_role)
    LinearLayout selectRole;
    @Bind(R.id.password_again_edit)
    EditText passwordAgainEdit;
    @Bind(R.id.password_again_delete)
    ImageView passwordAgainDelete;
    @Bind(R.id.join_class)
    LinearLayout joinClass;
    @Bind(R.id.confirm)
    Button confirm;
    @Bind(R.id.teacher_role)
    LinearLayout teacherRole;
    @Bind(R.id.student_role)
    LinearLayout studentRole;
    @Bind(R.id.creat_class)
    TextView creatClass;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.creat_class_temp1)
    RelativeLayout creatClassTemp1;

    @Bind(R.id.creat_class_temp)
    LinearLayout creatClassTemp;
    @Bind(R.id.creat_class_ll)
    LinearLayout creatClassLl;


    CartoonTeacherClassListAdapter cartoonClassListAdapter;

    ArrayList<CartoonTeacherListClassDataBean.ClassVOBean> itemDatas;
    @Bind(R.id.top_LL)
    RelativeLayout topLL;
    @Bind(R.id.join)
    Button join;
    @Bind(R.id.search_src_text)
    TextView searchSrcText;
    @Bind(R.id.serch_tv)
    RelativeLayout serchTv;
    @Bind(R.id.temp1)
    TextView temp1;
    @Bind(R.id.temp2)
    TextView temp2;
    @Bind(R.id.temp3)
    ImageView temp3;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_new_school, container, false);
        ButterKnife.bind(this, view);


        if (SPUtils.gettStudentRole()) {
            isStudent = true;
            teacherRole.setBackground(null);
            studentRole.setBackgroundResource(R.drawable.cartoon_select_role);
        } else if (SPUtils.gettTeacherRole()) {
            isConfrim = true;
            creatClass.setVisibility(View.VISIBLE);
            joinClass.setVisibility(View.GONE);
            selectRole.setVisibility(View.GONE);

            creatClassLl.setVisibility(View.VISIBLE);

            creatClassTemp.setVisibility(View.GONE);
            creatClassTemp1.setVisibility(View.VISIBLE);


            if (cartoonClassListAdapter == null) {
                itemDatas = new ArrayList<>();
                cartoonClassListAdapter = new CartoonTeacherClassListAdapter(getActivity(), itemDatas);
                cartoonClassListAdapter.setOnLongClickCallBack(new CartoonTeacherClassListAdapter.OnLongClickCallBack() {
                    @Override
                    public void CallBack(CartoonTeacherListClassDataBean.ClassVOBean item, int position) {
                        delteClass(item.getClassId(), item.getClassName(), position);
                    }

                });


                LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
                linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

                recyclerView.setLayoutManager(linearLayoutManager);
                recyclerView.setAdapter(cartoonClassListAdapter);
            }
        }


        return view;
    }


    @Override
    public void onResume() {
        super.onResume();
        LogUtil.MyLog("setUserVisibleHint", "onResume");
        if (isConfrim) {

            if (SPUtils.gettTeacherRole()) {
                getTeacherClassList();
            }

        }

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        if (!hidden) {
            LogUtil.MyLog("setUserVisibleHint", "显示出来了");
            if (SPUtils.gettStudentRole()) {

                if (TextUtils.isEmpty(SPUtils.getClassID())) {

                    swapIdentify("0");
//                    getClassList();
                }

            } else if (SPUtils.gettTeacherRole()) {
                swapIdentify("1");

            } else {
                joinClass.setVisibility(View.GONE);
                selectRole.setVisibility(View.VISIBLE);
                creatClassLl.setVisibility(View.GONE);
                creatClass.setVisibility(View.GONE);
            }
        } else {
            LogUtil.MyLog("setUserVisibleHint", "hidden");
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    boolean isStudent = true;

    @OnClick({R.id.student_role, R.id.serch_tv, R.id.teacher_role, R.id.confirm, R.id.join, R.id.select_role, R.id.password_again_delete, R.id.join_class, R.id.creat_class})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.serch_tv:
                Intent intent2 = new Intent(getActivity(), CartoonSearchActivity.class);
                getActivity().startActivity(intent2);
                break;
            case R.id.teacher_role:
                isStudent = false;
                studentRole.setBackground(null);
                teacherRole.setBackgroundResource(R.drawable.cartoon_select_role);
                break;
            case R.id.student_role:
                isStudent = true;
                teacherRole.setBackground(null);
                studentRole.setBackgroundResource(R.drawable.cartoon_select_role);
                break;
            case R.id.confirm:

                if (isStudent) {
                    swapIdentify("0");
//
//                    getClassList();

                } else {

                    swapIdentify("1");
//                    creatClass.setVisibility(View.VISIBLE);
//
//                    if (cartoonClassListAdapter == null) {
//                        itemDatas = new ArrayList<>();
//                        cartoonClassListAdapter = new CartoonTeacherClassListAdapter(getActivity(), itemDatas);
//
//                        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
//                        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
//
//                        recyclerView.setLayoutManager(linearLayoutManager);
//                        recyclerView.setAdapter(cartoonClassListAdapter);
//                    }
//
//
//                    getTeacherClassList();

                }

                break;
            case R.id.select_role:
                break;
            case R.id.password_again_delete:
                break;
            case R.id.join:
                joinclass();
                break;
            case R.id.join_class:
                break;
            case R.id.creat_class:
                checkCreateClassNum();
//

                break;
        }
    }


    boolean isConfrim = false;

    private void joinclass() {
        String editStr = passwordAgainEdit.getText().toString();
        Map<String, Object> map = new HashMap<>();
        map.put("classNo", editStr);
        HttpMehtod.getInstance().cartoonJoinClass(map, new CustomNetSubscriber(getActivity()) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                BaseBean<CartoonJoinClassResultBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonJoinClassResultBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonJoinClassResultBean>() {
                    @Override
                    public void success(CartoonJoinClassResultBean dataBean) {
                        ToastUtil.show("班级加入成功");

                        SPUtils.putClassID(dataBean.getResult().getClassId() + "," + dataBean.getResult().getClassName());
                        MyApplication.classIDStr = dataBean.getResult().getClassId() + "";
                        MyApplication.classNameStr = dataBean.getResult().getClassName() + "";

                        Intent intent = new Intent(getActivity(), CartoonChildHomeActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void fail(String errorCode) {
                    }
                }).dealData();
            }
        });

    }


    private void getClassList() {
        Map<String, Object> map = new HashMap<>();
        HttpMehtod.getInstance().cartoonListOfClass(map, new CustomNetSubscriber(getActivity(), true) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                BaseBean<CartoonClassListBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonClassListBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonClassListBean>() {
                    @Override
                    public void success(CartoonClassListBean dataBean) {

                        if (dataBean.getResult() != null && dataBean.getResult().size() > 0) {
                            MyApplication.classNameStr = dataBean.getResult().get(0).getClassName();
                            MyApplication.classIDStr = dataBean.getResult().get(0).getClassId() + "";
                            SPUtils.putClassID(MyApplication.classIDStr + "," + MyApplication.classNameStr);


                            LogUtil.MyLog("putStudentRole", "======getClassList======");
                            SPUtils.putStudentRole(true);
                            SPUtils.putTeacherRole(false);

                            Intent intent = new Intent(getActivity(), CartoonChildHomeActivity.class);
                            startActivityForResult(intent, MainActivity.CARTOON_SUDENT);
                        } else {
                            LogUtil.MyLog("CartoonClassListBean", "=======CartoonClassListBean===");

                            joinClass.setVisibility(View.VISIBLE);
                            selectRole.setVisibility(View.GONE);
                            creatClassLl.setVisibility(View.GONE);
                            creatClass.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void fail(String errorCode) {

                        joinClass.setVisibility(View.VISIBLE);
                        selectRole.setVisibility(View.GONE);
                        creatClassLl.setVisibility(View.GONE);
                        creatClass.setVisibility(View.GONE);
                    }


                }).dealData();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);

                joinClass.setVisibility(View.VISIBLE);
                selectRole.setVisibility(View.GONE);
            }
        });

    }

    //    swapType  1老师 0学生
    private void swapIdentify(final String swapType) {
        Map<String, Object> map = new HashMap<>();
        map.put("swapType", swapType);
        HttpMehtod.getInstance().swapIdentify(map, new CustomNetSubscriber(getActivity(), false) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                BaseBean<CartoonRoleDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonRoleDataBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonRoleDataBean>() {
                    @Override
                    public void success(CartoonRoleDataBean dataBean) {

                        if (swapType.equals("0")) {

                            if (!TextUtils.isEmpty(dataBean.getId())) {
                                getClassList();
                            } else {
                                joinClass.setVisibility(View.VISIBLE);
                                selectRole.setVisibility(View.GONE);
                                creatClassLl.setVisibility(View.GONE);
                                creatClass.setVisibility(View.GONE);

                            }

                        } else if (swapType.equals("1")) {
                            if (!TextUtils.isEmpty(dataBean.getId())) {
                                isConfrim = true;
                                creatClass.setVisibility(View.VISIBLE);

                                if (cartoonClassListAdapter == null) {
                                    itemDatas = new ArrayList<>();
                                    cartoonClassListAdapter = new CartoonTeacherClassListAdapter(getActivity(), itemDatas);
                                    cartoonClassListAdapter.setOnLongClickCallBack(new CartoonTeacherClassListAdapter.OnLongClickCallBack() {
                                        @Override
                                        public void CallBack(CartoonTeacherListClassDataBean.ClassVOBean item, int position) {
                                            delteClass(item.getClassId(), item.getClassName(), position);
                                        }

                                    });

                                    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
                                    linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

                                    recyclerView.setLayoutManager(linearLayoutManager);
                                    recyclerView.setAdapter(cartoonClassListAdapter);
                                }


                                getTeacherClassList();
                            } else {
                                ToastUtil.show("用户不是老师");

                                joinClass.setVisibility(View.GONE);
                                selectRole.setVisibility(View.VISIBLE);
                                creatClassLl.setVisibility(View.GONE);
                                creatClass.setVisibility(View.GONE);
                            }
                        }

                    }

                    @Override
                    public void fail(String errorCode) {
                        joinClass.setVisibility(View.GONE);
                        selectRole.setVisibility(View.VISIBLE);
                        creatClassLl.setVisibility(View.GONE);
                        creatClass.setVisibility(View.GONE);

                    }
                }).dealData();
            }

        });
    }

    private void getTeacherClassList() {
        Map<String, Object> map = new HashMap<>();
        HttpMehtod.getInstance().getListClass(map, new CustomNetSubscriber(getActivity(), false) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {


                BaseBean<CartoonTeacherListClassDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonTeacherListClassDataBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonTeacherListClassDataBean>() {
                    @Override
                    public void success(CartoonTeacherListClassDataBean dataBean) {

                        LogUtil.MyLog("putStudentRole", "=====asdas=getClassList======");

                        SPUtils.putStudentRole(false);
                        SPUtils.putTeacherRole(true);

                        cartoonClassListAdapter.notifyDataSetChanged(dataBean.getClassVO());


                        joinClass.setVisibility(View.GONE);
                        selectRole.setVisibility(View.GONE);

                        creatClassLl.setVisibility(View.VISIBLE);

                        creatClassTemp.setVisibility(View.GONE);
                        creatClassTemp1.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void fail(String errorCode) {

                        joinClass.setVisibility(View.GONE);
                        selectRole.setVisibility(View.GONE);

                        creatClassLl.setVisibility(View.VISIBLE);

                        creatClassTemp.setVisibility(View.VISIBLE);
                        creatClassTemp1.setVisibility(View.GONE);

                    }
                }).dealData();
            }

        });
    }


    private void checkCreateClassNum() {
        Map<String, Object> map = new HashMap<>();
        HttpMehtod.getInstance().checkCreateClassNum(map, new CustomNetSubscriber(getActivity(), false) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {


                BaseBean<CheckCreatClassDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CheckCreatClassDataBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CheckCreatClassDataBean>() {
                    @Override
                    public void success(CheckCreatClassDataBean dataBean) {
                        Intent intent = new Intent(getActivity(), CartoonCreatClassActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }

        });
    }

    PromptPopupWindow promptDialog;

    private void delteClass(final String classId, final String className, final int position) {


        if (promptDialog == null) {
            promptDialog = new PromptPopupWindow(getActivity(), topLL);
            promptDialog.setCallBack(new PromptPopupWindow.CallBack() {
                @Override
                public void confirm() {
                    deletClassData(classId, className, position);
                }

                @Override
                public void cancle() {

                }
            });
            promptDialog.setPromptTitle("是否确定删除班级？");
        }

        promptDialog.showPopupWindow();

    }

    private void deletClassData(String classId, String className, final int position) {

        Map<String, Object> map = new HashMap<>();

        map.put("classId", classId);
        map.put("className", className);
        HttpMehtod.getInstance().deleteClass(map, new CustomNetSubscriber(getActivity(), false) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {


                BaseBean<CheckCreatClassDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CheckCreatClassDataBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CheckCreatClassDataBean>() {
                    @Override
                    public void success(CheckCreatClassDataBean dataBean) {

                        if (dataBean.isResult()) {
                            ToastUtil.show("删除成功");
                            cartoonClassListAdapter.itemDatas.remove(position);
                            cartoonClassListAdapter.notifyDataSetChanged();

                        }

                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }

        });
    }

}

